package com.bjpowernode.threadpool.shutdown;

import com.bjpowernode.util.ThreadUtils;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Test04 {

    //基于Executor框架实现线程池
    private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            8,
            16,
            15,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(1024),
            Executors.defaultThreadFactory(),
            //Executors.privilegedThreadFactory(),
            new ThreadPoolExecutor.DiscardOldestPolicy()
    );

    public static void main(String[] args) {
        System.out.println("main方法执行开始........");
        doSomeThing1();
        doSomeThing2();
        System.out.println("main方法执行结束........");
    }

    public static void doSomeThing1() {
        for (int i = 0; i < 10; i++) {
            threadPoolExecutor.execute(() -> {
                ThreadUtils.sleepMilliSeconds(200);
                System.out.println("线程执行任务 1 ......");
            });
        }
        //关闭线程池
        threadPoolExecutor.shutdown();
        try {
            while (!threadPoolExecutor.awaitTermination(100, TimeUnit.MILLISECONDS)) {
                System.out.println("线程池还在运行 1 ......");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程池已经完全关闭 1 ......");
    }

    public static void doSomeThing2() {
        for (int i = 0; i < 5; i++) {
            System.out.println("doSomeThing2 。。。。。。");
            threadPoolExecutor.execute(() -> {
                System.out.println(" 2222222222222222222 ");
                ThreadUtils.sleepMilliSeconds(200);
                System.out.println("线程执行任务 2 ......");
            });
        }
        //关闭线程池
        threadPoolExecutor.shutdown();
        try {
            while (!threadPoolExecutor.awaitTermination(100, TimeUnit.MILLISECONDS)) {
                System.out.println("线程池还在运行 2 ......");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程池已经完全关闭 2 ......");
    }
}
